package com.demo.base.webView.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.base.http.HttpClientHelper;
import com.demo.base.redis.helper.RedisHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description 获取调用JS的票据
 * @date 2023/4/4 2:27 PM
 */
@Component
@Slf4j
public class JjApiTicket {

    /** 注入获取access_token组件 */
    @Autowired private JsAccessToken jsAccessToken;

    @Autowired
    public JjApiTicket(JsAccessToken jsAccessToken) {
        this.jsAccessToken = jsAccessToken;
    }

    /** 注入Redis */
    private RedisHelper redisHelper;

    @Autowired
    public void setRedisHelper(RedisHelper redisHelper) {
        this.redisHelper = redisHelper;
    }

    @PostConstruct
    public void init() {
        // 获取调用JS的票据
        getTicket();
    }

    // 开启轮询器
    // 执行间隔：100分钟
    @Scheduled(fixedDelay = 100 * 60 * 1000)
    public void start() {
        // 获取调用JS的票据
        getTicket();
    }

    public void getTicket() {

        log.debug("获取调用JS的票据");

        // 1.获取access_token
        String accessTokenString = jsAccessToken.getAccessToken();
        if (StringUtils.isBlank(accessTokenString)) {
            log.error("获取调用JS的accessToken失败");

            return;
        }

        // 2.拼接URL
        String url =
                "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
                        + accessTokenString
                        + "&type=jsapi";

        // 3.执行请求
        String result = HttpClientHelper.doGet(url);
        // 4.判断请求是否成功
        if (StringUtils.isBlank(result)) {
            log.error("获取调用JS的票据失败");

            return;
        }

        // 5.解析结果
        JSONObject jsonObject = JSON.parseObject(result);
        // 判断状态码
        if (jsonObject.getInteger("errcode") != 0) {
            log.error("获取调用JS的票据失败");

            return;
        }

        // 6.从结果获取ticket
        String ticket = jsonObject.getString("ticket");
        if (StringUtils.isBlank(ticket)) {
            log.error("获取调用JS的票据失败");

            return;
        }

        // 存储ticket到Redis，有效时间110min
        redisHelper.set("WeXinJsApiTicket", ticket, 110 * 60 * 1000L);
    }
}
